﻿using System;
using System.Configuration;
using System.IO;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using MessageBox = System.Windows.Forms.MessageBox;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;

namespace ScreenGrab
{
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
      Loaded += mainWindow_Loaded;

    }

    public static readonly RoutedEvent MediaLoadedEvent;
    public string SaveAs = string.Empty;

    static Window1()
    {
      MediaLoadedEvent = EventManager.RegisterRoutedEvent("MediaLoaded", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Window1));
    }

    public event RoutedEventHandler MediaLoaded
    {
      add { AddHandler(MediaLoadedEvent, value); }
      remove { RemoveHandler(MediaLoadedEvent, value); }
    }



    private MediaPlayer player = new MediaPlayer();
    private string filename = string.Empty;
    private int i = 0;

    private void button1_Click(object sender, RoutedEventArgs e)
    {



    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
      if (Pause.Content == "Resume")
      {
        clock.Controller.Resume();
        Pause.Content = "Pause";
      }
      else
      {
        clock.Controller.Pause();
        Pause.Content = "Resume";

      }
    }

    public void Grab()
    {
      i++;
      clock.Controller.Pause();
      RenderTargetBitmap rtb = new RenderTargetBitmap(player.NaturalVideoWidth, player.NaturalVideoHeight, 1 / 200, 1 / 200, PixelFormats.Pbgra32);
      DrawingVisual dv = new DrawingVisual();
      DrawingContext dc = dv.RenderOpen();

      dc.DrawVideo(player, new Rect(0, 0, player.NaturalVideoWidth, player.NaturalVideoHeight));
      dc.Close();
      rtb.Render(dv);

      ConfigurationManager.RefreshSection("ImageStore");
      ConfigurationManager.RefreshSection("SaveAs");

      PngBitmapEncoder png = new PngBitmapEncoder();
      png.Frames.Add(BitmapFrame.Create(rtb));

      JpegBitmapEncoder jpg = new JpegBitmapEncoder();
      jpg.Frames.Add(BitmapFrame.Create(rtb));

      string imageStore = ReadSetting("ImageStore");
      string fileExt = ReadSetting("SaveAs");
      using (Stream stm = File.Create(@imageStore + "\\" + i.ToString() + "." + fileExt))
      {
        if (fileExt == "PNG")
          png.Save(stm);
        else
          jpg.Save(stm);

      }
      clock.Controller.Resume();
    }

    private void button3_Click(object sender, RoutedEventArgs e)
    {
      ConfigurationManager.RefreshSection("ImageBurst");
      ConfigurationManager.RefreshSection("ImageBurstFrames");

      string ib = ReadSetting("ImageBurst");
      Int32 ibf = Convert.ToInt32( ReadSetting("ImageBurstFrames"));
      if (ib == "True")
      {
        for (int j = 0; j < ibf; j++)
        {
          Grab();
        }
      }
      else
      {
        Grab();
      }
    }

    public static string ReadSetting(string key)
    {
      //System.Configuration.AppSettingsReader reader = new AppSettingsReader();
      //return reader.GetValue(key,String);
      //return System.Configuration.ConfigurationManager.AppSettings[key];
      ImageStoreData configData = ConfigurationManager.GetSection(key) as ImageStoreData;
      return configData.ImageStore;
      //return ConfigurationSettings.AppSettings[key];
    }


    private void player_MediaOpened(object sender, EventArgs e)
    {
      MessageBox.Show("test");
    }

    private MediaClock clock;
    private MediaTimeline timeline;

    private void button5_Click(object sender, RoutedEventArgs e)
    {
      ConfigurationManager.RefreshSection("ImageStore");
      try
      {
        if (ReadSetting("ImageStore") == null)
        {
          MessageBox.Show("Go to options and set the required fields before you start grabbing","Codename \"ScreenGrab\"");
          
        }
        else
        {
          OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();

          dlg.Filter = "Media files (*.wmv,*.mpg,*.m2ts)|*.wmv;*.mpg;*.m2ts|All Files (*.*)|*.*";
          dlg.RestoreDirectory = true;

          if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
          {
            filename = dlg.FileName;
            timeline = new MediaTimeline(new Uri(filename, UriKind.Relative));
            //timeline.RepeatBehavior = RepeatBehavior.Forever;

            clock = timeline.CreateClock();



            //player.SpeedRatio = 10000;

            player.Clock = clock;


            // Create the VideoDrawing.
            VideoDrawing videoDrawing = new VideoDrawing();
            videoDrawing.Rect = new Rect(150, 0, 100, 100);
            videoDrawing.Player = player;
            // Assign the DrawingBrush.
            DrawingBrush brush = new DrawingBrush(videoDrawing);
            //this.Background = brush;
            frame1.Background = brush;

            //player.SpeedRatio = 2; 

            // Start the timeline.
            clock.Controller.Begin();



            Pause.IsEnabled = true;
            Screenshot.IsEnabled = true;
            slider1.IsEnabled = true;

            //player.SpeedRatio = 2; 

            //Load Save As image file
            ConfigurationManager.RefreshSection("SaveAs");
            SaveAs = ReadSetting("SaveAs");
            //MessageBox.Show(SaveAs);

            player.MediaOpened += new EventHandler(player_MediaOpened1);
            clock.CurrentTimeInvalidated += new EventHandler(clock_CurrentTimeInvalidated);
            bool ts = player.NaturalDuration.HasTimeSpan;
            if (ts)
            {
              slider1.Maximum = Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds);
            }
            //if (clock != null) clock.Controller.SpeedRatio = 2;
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show("Go to options and set the required fields before you start grabbing");
      }

      
    }

    void clock_CurrentTimeInvalidated(object sender, EventArgs e)
    {
      if (_enableSliderAutoUpdate)
        slider1.Value = player.Position.Ticks;
      //label2.Content =  player.Position.Duration() + " // " + player.NaturalDuration;
      string hrs = string.Empty;
      string min = string.Empty;
      string sec = string.Empty;
      string durhrs = string.Empty;
      string durmin = string.Empty;
      string dursec = string.Empty;

      if (player.Position.Hours < 10)
        hrs = "0" + player.Position.Hours;
      else
        hrs = player.Position.Hours.ToString();

      if (player.Position.Minutes < 10)
        min = "0" + player.Position.Minutes;
      else
        min = player.Position.Minutes.ToString();

      if (player.Position.Seconds < 10)
        sec = "0" + player.Position.Seconds;
      else
        sec = player.Position.Seconds.ToString();

      if (player.NaturalDuration.TimeSpan.Hours < 10)
        durhrs = "0" + player.NaturalDuration.TimeSpan.Hours;
      else
        durhrs = player.NaturalDuration.TimeSpan.Hours.ToString();

      if (player.NaturalDuration.TimeSpan.Minutes < 10)
        durmin = "0" + player.NaturalDuration.TimeSpan.Minutes;
      else
        durmin = player.NaturalDuration.TimeSpan.Minutes.ToString();

      if (player.NaturalDuration.TimeSpan.Seconds < 10)
        dursec = "0" + player.NaturalDuration.TimeSpan.Seconds;
      else
        dursec = player.NaturalDuration.TimeSpan.Seconds.ToString();

      label2.Content = string.Format("{0}:{1}:{2}", hrs, min, sec) + " / " +
                       string.Format("{0}:{1}:{2}", durhrs, durmin, dursec);

    }

    public void player_MediaOpened1(object sender, EventArgs e)
    {
      //mainWindow.Width = player.NaturalVideoWidth;
      //mainWindow.Height = player.NaturalVideoHeight+105;
      //frame1.Height = player.NaturalVideoHeight;
      //frame1.Width = player.NaturalVideoWidth;
      //topRow.Height = new GridLength(player.NaturalVideoHeight+10);
      sbRes.Content = "Resuloution: " + player.NaturalVideoWidth + "x" + player.NaturalVideoHeight;

      slider1.Maximum = player.NaturalDuration.TimeSpan.Ticks;
    }

    private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {

    }

    private void slider1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
    }

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {

    }

    public TimeSpan SliderTime;

    private void slider1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
      //clock.Controller.Pause();

    }

    private void slider1_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {


      ////clock. = myts;
      ////SliderTime.Add() =;
      //slider1.Maximum = Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds);
      ////MessageBox.Show(slider1.Maximum.ToString());
      //slider1.Ticks.Add(Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds));
      ////MessageBox.Show(slider1.Ticks.ToString());
      ////slider1.Ticks.
      //MessageBox.Show(Math.Round(slider1.Value).ToString());
      //TimeSpan seektime = TimeSpan.Parse(Math.Round(slider1.Value).ToString());
      //player.Clock.Controller.Seek(seektime, TimeSeekOrigin.BeginTime);
      ////MessageBox.Show(SliderTime.ToString());
      ////player.Position.Add(SliderTime);
      //clock.Controller.Resume();

      //slider1.Maximum = Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds);
      ////MessageBox.Show(slider1.Maximum.ToString());
      //slider1.Ticks.Add(Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds));

    }

    private void slider1_StylusButtonDown(object sender, StylusButtonEventArgs e)
    {

    }

    private void slider1_StylusButtonUp(object sender, StylusButtonEventArgs e)
    {

    }

    private void slider1_MouseDown(object sender, MouseButtonEventArgs e)
    {

    }

    private void slider1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
      //clock.Controller.Pause();
    }

    private void slider1_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
      ////clock. = myts;
      ////SliderTime.Add() =;
      //slider1.Maximum = Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds);
      //MessageBox.Show(slider1.Maximum.ToString());
      //slider1.Ticks.Add(Convert.ToDouble(player.NaturalDuration.TimeSpan.Milliseconds));
      //MessageBox.Show(slider1.Ticks.ToString());
      ////slider1.Ticks.
      //MessageBox.Show(slider1.Value.ToString());
      ////TimeSpan seektime = TimeSpan.Parse(slider1.Value.ToString());
      ////player.Clock.Controller.Seek(seektime, TimeSeekOrigin.BeginTime);
      ////MessageBox.Show(SliderTime.ToString());
      ////player.Position.Add(SliderTime);
      //clock.Controller.Resume();
    }

    private bool _enableSliderAutoUpdate = true;

    private Thumb sliderThumb;
    private void mainWindow_Loaded(object sender, RoutedEventArgs e)
    {
      Track sliderTrack = slider1.Template.FindName("PART_Track", slider1) as Track;
      if (sliderTrack != null) sliderThumb = sliderTrack.Thumb;
      sliderThumb.DragCompleted += sliderThumb_DragCompleted;
      sliderThumb.PreviewMouseLeftButtonDown += sliderThumb_PreviewMouseLeftButtonDown;
    }

    private void sliderThumb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      _enableSliderAutoUpdate = false;
    }

    private void sliderThumb_DragCompleted(object sender, DragCompletedEventArgs e)
    {
      player.Clock.Controller.Seek(new TimeSpan((long)slider1.Value), TimeSeekOrigin.BeginTime);
      _enableSliderAutoUpdate = true;
    }

    private void MenuItem_Click_1(object sender, RoutedEventArgs e)
    {
      options opt = new options();
      opt.ShowDialog();
    }

    private void button1_Click_1(object sender, RoutedEventArgs e)
    {
      string store = ReadSetting("ImageStore");
      MessageBox.Show(store);
    }
  }
}
